#!/usr/bin/python3

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

import argparse
import subprocess
import os.path

# 输入源代码文件路径，返回编译器字符串
def get_compiler(filepath: str) -> str:
    extension = filepath.split('.')[-1]
    if extension == 'c':
        return "gcc"
    elif extension == 'cpp':
        return "g++"
    else:
        raise ValueError("必须是.c结尾或者.cpp结尾的文本文件")

# 输入源代码文件路径并编译
def compile(cc: str, filepath: str, exepath: str):
    command = [cc, filepath, "-o", exepath]
    # 编译
    result = subprocess.run(command, capture_output=True, text=True)
    assert result.returncode==0, "编译失败"

def edit_inputfile(ifpath):
    if not os.path.exists(ifpath):
        print("输入文件不存在，将会尝试创建一个")
        with open(ifpath, 'w', encoding="utf-8") as file:
            file.write("\n")

    command = ["vim", ifpath]
    result = subprocess.run(command)
    assert result.returncode==0, "写入失败"

# 执行可执行文件，输入编译后的可执行文件路径 和 输入文件
def exec_alg(execpath: str, ifpath: str):
    if not execpath.startswith("/") and not execpath.startswith("./"):
        execpath = "./"+execpath

    with open(ifpath, 'r') as f:
        subprocess.run([execpath], stdin=f)

def main():
    parser = argparse.ArgumentParser(description='能让你更方便地写c/c++算法题的一个脚本而已')

    parser.add_argument('-f', '--file', help='输入代码源文件路径', required=True)

    args = parser.parse_args()

    filepath = args.file
    assert os.path.exists(filepath), "代码文件不存在"

    cc = get_compiler(filepath)
    # 父级文件夹路径
    parent_dir = os.path.dirname(filepath)
    # 文件名
    basename = os.path.basename(filepath)
    # 扔掉后缀的文件名
    stem_name = os.path.splitext(basename)[0]
    # 编译后可执行文件的路径
    exepath = os.path.join(parent_dir, stem_name)

    compile(cc, filepath, exepath)

    ifpath = exepath+".in"
    edit_inputfile(ifpath)

    exec_alg(exepath, ifpath)

if __name__ == '__main__':
    main()